/*
 * @lc app=leetcode.cn id=2487 lang=csharp
 *
 * [2487] 从链表中移除节点
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int val=0, ListNode next=null) {
 *         this.val = val;
 *         this.next = next;
 *     }
 * }
 */
public class Solution {
     public ListNode RemoveNodes(ListNode head) {
        head = Reverse(head);
        for (ListNode p = head; p.next != null; ) {
            if (p.val > p.next.val) {
                p.next = p.next.next;
            } else {
                p = p.next;
            }
        }
        return Reverse(head);
    }

    public ListNode Reverse(ListNode head) {
        ListNode dummy = new ListNode();
        while (head != null) {
            ListNode p = head;
            head = head.next;
            p.next = dummy.next;
            dummy.next = p;
        }
        return dummy.next;
    }
}
// @lc code=end

